package org.the.gsdo.server;

import java.lang.reflect.Method;
import java.util.logging.Logger;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

//spring must scan this class (see ApplicationConfiguration :: basePackageClasses
@Component
// aspectj
@Aspect
@Profile("dev")
public class LogAspectDev extends LogAspect {

	private static Logger log = Logger.getLogger(LogAspect.class.getName());

	@Around("anyPublicMethod() && @annotation(logAction)")
	public Object logAction(ProceedingJoinPoint pjp, LogAction logAction)
			throws Throwable {
		String actionPerformed = logAction.value();
		// Do what you want with the join point arguments
		Object target = pjp.getTarget();
		MethodSignature signature = (MethodSignature) pjp.getSignature();
		Method method = signature.getMethod();
		Object[] args = pjp.getArgs();
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (Object arg : args) {
			if (i > 0) {
				sb.append(", ");
			}
			sb.append(String.valueOf(arg));
			i++;
		}
		long start = System.nanoTime();
		log.info("++>> entry [" + actionPerformed + "], start(nano) = " + start +
				", method = " + method.getName() + ", target = " + target +
				", args = (" + sb.toString() + ")");
		Object ret = pjp.proceed();
		long end = System.nanoTime();
		long diff = end - start;
		log.info("<<++ exit [" + actionPerformed + "], end(nano) = " + end + ", time(nano) = " + diff);
		return ret;
	}

}
